﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.IO;

namespace Department.admin.Content
{
    public partial class EditDynamicContent : System.Web.UI.Page
    {
        private string strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["DepartmentConnectionString"].ConnectionString;
        const int MAX_FILE_SIZE = AdminVariablesSingleton.MAX_FILE_SIZE;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Request.IsAuthenticated)
            {
                Response.Redirect("/admin/Login.aspx");
            }
            if (Request.Params["ID"] == null) // Redirect user if the page is loaded without params
            {
                Response.Redirect("/admin/Content/ViewAllDynamicContent.aspx");
            }

            this.Page.Title = "Редакция на динамично съдържание";

            AdminVariablesSingleton.configureCKEditor(ref CKEditor);
            
            string heading;
            DateTime date;
            string text;
            bool isHidden;
            int type;
            string id = Request.Params["ID"];
            if (!Page.IsPostBack)
            {
                if (!(id == null))
                {
                    SqlConnection conn = new SqlConnection(strConnString);

                    try
                    {
                        conn.Open();

                        //Gets the news heading
                        string sqlHeading = "SELECT Name From DynamicContent WHERE ID = @ID AND FacDeptID = dbo.uf_get_department_id()";
                        SqlCommand comHeading = new SqlCommand(sqlHeading, conn);
                        comHeading.Parameters.AddWithValue("@ID", id);
                        heading = Convert.ToString(comHeading.ExecuteScalar());
                        TextBoxHeading.Text = heading;

                        //Gets the news text
                        string sqlText = "SELECT Text From DynamicContent WHERE ID = @ID AND FacDeptID = dbo.uf_get_department_id()";
                        SqlCommand comText = new SqlCommand(sqlText, conn);
                        comText.Parameters.AddWithValue("@ID", id);
                        text = Convert.ToString(comText.ExecuteScalar());
                        CKEditor.Text = text;

                        //Checks if the news is hidden or not
                        string sqlIsHidden = "SELECT IsHidden FROM DynamicContent WHERE ID = @ID AND FacDeptID = dbo.uf_get_department_id()";
                        SqlCommand comIsHidden = new SqlCommand(sqlIsHidden, conn);
                        comIsHidden.Parameters.AddWithValue("@ID", id);
                        isHidden = Convert.ToBoolean(comIsHidden.ExecuteScalar());
                        checkboxActive.Checked = isHidden;

                        string sqlDate = "SELECT Date FROM DynamicContent WHERE ID = @ID AND FacDeptID = dbo.uf_get_department_id()";
                        SqlCommand comDate = new SqlCommand(sqlDate, conn);
                        comDate.Parameters.AddWithValue("@ID", id);
                        date = DateTime.Parse(comDate.ExecuteScalar().ToString());
                        TextBoxDate.Text = date.ToShortDateString();


                        string sqlType = "SELECT TypeID FROM DynamicContent WHERE ID = @ID AND FacDeptID = dbo.uf_get_department_id()";
                        SqlCommand comType = new SqlCommand(sqlType, conn);
                        comType.Parameters.AddWithValue("@ID", id);
                        type = Convert.ToInt32(comType.ExecuteScalar());
                        typeIDDropDownList.SelectedValue = type.ToString();
                        TextBoxDate.Text = date.ToShortDateString();


                    }
                    catch (SqlException sqle)
                    {
                        Response.Redirect("/admin/ErrorPage.aspx?type=sql&err=" + sqle.Message);
                    }
                    catch (Exception ex)
                    {
                        Response.Redirect("/admin/ErrorPage.aspx?type=1&err=" + ex.Message);
                    }
                    finally
                    {
                        conn.Close();
                    }

                }

            }

        }

        protected void buttonSubmit_Click(object sender, EventArgs e)
        {
            FileInfo[] arrayWithFileNames = new FileInfo[3];
            arrayWithFileNames = this.uploadFiles();
            string eventID = Request.Params["ID"];
            SqlConnection conn = new SqlConnection(strConnString);
            try
            {
                conn.Open();
                string sqlUpdate = "UPDATE DynamicContent SET Name=@Heading, Text=@Text, TypeID=@TypeID, IsHidden=@IsMain, Date=@Date WHERE ID = @ID";
                SqlCommand comUpdate = new SqlCommand(sqlUpdate, conn);
                string meca = TextBoxHeading.Text;
                comUpdate.Parameters.AddWithValue("@ID", Request.Params["ID"]);
                comUpdate.Parameters.AddWithValue("@Heading", TextBoxHeading.Text);
                comUpdate.Parameters.AddWithValue("@Text", CKEditor.Text);
                comUpdate.Parameters.AddWithValue("@TypeID", typeIDDropDownList.SelectedValue);
                comUpdate.Parameters.AddWithValue("@IsMain", checkboxActive.Checked);
                comUpdate.Parameters.AddWithValue("@Date", DateTime.Parse(TextBoxDate.Text));
       
                comUpdate.ExecuteNonQuery();

            }
            catch (SqlException sqle)
            {
                Response.Redirect("/admin/ErrorPage.aspx?type=sql&err=" + sqle.Message);
            }
            catch (Exception ex)
            {
                Response.Redirect("/admin/ErrorPage.aspx?type=1&err=" + ex.Message);
            }
            finally
            {
                conn.Close();
            }
            if (!eventID.Equals(""))
            {
                if (arrayWithFileNames[0] != null)
                {
                    insertDocumentForNews(arrayWithFileNames[0], eventID);
                }
                if (arrayWithFileNames[1] != null)
                {
                    insertDocumentForNews(arrayWithFileNames[1], eventID);
                }
                if (arrayWithFileNames[2] != null)
                {
                    insertDocumentForNews(arrayWithFileNames[2], eventID);
                }
            }
            Response.Redirect("~/admin/Content/ViewAllDynamicContent.aspx");
        }
        protected FileInfo uploadFile(FileUpload fileControl)
        {
            if (fileControl.HasFile)
            {
                try
                {
                    if (fileControl.PostedFile.ContentLength < MAX_FILE_SIZE)
                    {
                        FileInfo fileInfo = new FileInfo();
                        string filename = Path.GetFileName(fileControl.FileName);
                        fileInfo.OriginalFileName = filename;

                        filename = DateTime.Now.ToUniversalTime().ToFileTimeUtc() + filename;
                        fileInfo.UniqueFileName = filename;

                        fileControl.SaveAs(Server.MapPath("~/files/uploadedFiles/") + filename);
                        fileInfo.FilePath = "~/files/uploadedFiles/" + filename;
                        return fileInfo;
                    }
                }
                catch (Exception ex)
                {
                    Response.Redirect("/admin/ErrorPage.aspx?type=1&err=" + ex.Message);
                }
            }
            return null;
        }
        protected FileInfo[] uploadFiles()
        {
            FileInfo[] arrayWithFileNames = new FileInfo[3];
            int arrayCounter = 0;
            arrayWithFileNames[arrayCounter] = uploadFile(FileUploadControl);
            arrayCounter++;
            arrayWithFileNames[arrayCounter] = uploadFile(FileUploadControl2);
            arrayCounter++;
            arrayWithFileNames[arrayCounter] = uploadFile(FileUploadControl3);

            return arrayWithFileNames;
        }
        protected void insertDocumentForNews(FileInfo fileInfo, string dynContentID)
        {
            string strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["DepartmentConnectionString"].ConnectionString;
            SqlConnection conn = new SqlConnection(strConnString);
            try
            {
                conn.Open();
                string sqlCommandText = @"INSERT INTO Documents (Name, Description, Link, TypeID, FacDeptID) VALUES (@Name, @Description, @Link, (SELECT ID FROM Type WHERE Name = 'Documents'), dbo.uf_get_department_id())";
                SqlCommand insertDocument = new SqlCommand(sqlCommandText, conn);

                insertDocument.Parameters.AddWithValue("@Name", fileInfo.OriginalFileName);
                insertDocument.Parameters.AddWithValue("@Description", fileInfo.UniqueFileName);
                insertDocument.Parameters.AddWithValue("@Link", fileInfo.FilePath);

                insertDocument.ExecuteNonQuery();

                string sqlCommandText2 = "INSERT INTO DocumentsForContent (DynContentID, DocID) VALUES (@DynContentID, @@Identity)";
                SqlCommand insertDocumentForNews = new SqlCommand(sqlCommandText2, conn);

                insertDocumentForNews.Parameters.AddWithValue("@DynContentID", dynContentID);

                insertDocumentForNews.ExecuteNonQuery();
            }
            catch (SqlException sqle)
            {
                Response.Redirect("/admin/ErrorPage.aspx?type=sql&err=" + sqle.Message);
            }
            catch (Exception ex)
            {
                Response.Redirect("/admin/ErrorPage.aspx?type=1&err=" + ex.Message);
            }
            finally
            {
                conn.Close();
            }

        }
        protected void sortByHeading_Click(object sender, CommandEventArgs e)
        {


        }
        protected void markInactiveButton_Click(object sender, CommandEventArgs e)
        {
            string strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["DepartmentConnectionString"].ConnectionString;
            SqlConnection conn = new SqlConnection(strConnString);
            try
            {
                conn.Open();
                string sqlCommandText = "DELETE FROM DocumentsForContent WHERE DocID = @DocID; DELETE FROM Documents WHERE ID = @DocID";
                SqlCommand insertDocument = new SqlCommand(sqlCommandText, conn);

                insertDocument.Parameters.AddWithValue("@DocID", e.CommandArgument);


                insertDocument.ExecuteNonQuery();

            }
            catch (SqlException sqle)
            {
                Response.Redirect("/admin/ErrorPage.aspx?type=sql&err=" + sqle.Message);
            }
            catch (Exception ex)
            {
                Response.Redirect("/admin/ErrorPage.aspx?type=1&err=" + ex.Message);
            }
            finally
            {
                conn.Close();
            }
            itemsView.DataBind();

        }

        private static void markAnItemInactive(string ID)
        {
            string strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["DepartmentConnectionString"].ConnectionString;
            using (SqlConnection conn = new SqlConnection(strConnString))
            {
                try
                {
                    conn.Open();

                    //Get Site content
                    string sqlText = "UPDATE DynamicContent SET IsHidden=1 WHERE ID = @ID";
                    SqlCommand comText = new SqlCommand(sqlText, conn);
                    comText.Parameters.AddWithValue("@ID", ID);

                    comText.ExecuteNonQuery();
                }
                catch (SqlException sqle)
                {
                    sqle.ToString();
                }
                finally
                {
                    conn.Close();
                }
            }
        }
    }
}